package com.me.study.designPatterns.Singleton;

import com.me.common.util.SleepUtil;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicReference;

/**
 * CAS指令 实现单例模式
 *
 * @author ME
 * @date   2020/1/8
 */
public class CasSingleton {

    public static void main(String[] args) {
        int count = 1000;
        CyclicBarrier barrier = new CyclicBarrier(count);
        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    barrier.await();
                    CasSingleton.getInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, Integer.toString(i)).start();
        }
        SleepUtil.seconds(30);
    }

    private static final AtomicReference<CasSingleton> INSTANCE = new AtomicReference();

    private CasSingleton() {
        System.out.println("实例化了。。。");
    }

    public static CasSingleton getInstance() {
        for (; ; ) {
            CasSingleton singleton = INSTANCE.get();
            if (null != singleton) {
                return singleton;
            }

            singleton = new CasSingleton();
            if (INSTANCE.compareAndSet(null, singleton)) {
                return singleton;
            }
        }
    }
}
